//
//  LoginViewViewController.swift
//  FastDevelop
//
//  Created by IOS1 on 2025/6/27.
//

import UIKit

class LoginViewViewController: HalfViewViewController {

    //1:login 2:setup
    private var type = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        loginV.registerBlock = {
            self.registerAction()
        }
    }
    
    private func registerAction(){
        
        self.type = 2
        
        loginV.isHidden = true
        setupV.isHidden = false
        loginBtn.setImage(UIImage(named: "setup"), for: .normal)
    }
    
    @objc private func clickBackButton(){

        if type == 2 {
            
            loginV.isHidden = false
            setupV.isHidden = true
            self.type = 1
            loginBtn.setImage(UIImage(named: "login"), for: .normal)
        }else{
            self.navigationController?.popViewController(animated: true)
        }        
    }
    
    @objc private func clickCheckButton(){
        checkButton.isSelected = !checkButton.isSelected
    }
    
    @objc private func clickLoginButton(){

        if !checkButton.isSelected {
            showToast("Bitte stimmen Sie den Servicebedingungen und der Datenschutzrichtlinie zu！")
            return
        }
        if type == 2 {
            //注册
            guard let email = setupV.emailTextF.text, email.isValidEmail else {
                showToast("Fehler im E-Mail-Format!")
                return }
            guard let pwd = setupV.pwdTextF.text, pwd.isValidatePwd else {
                showToast("Passwort: 6-16 Zeichen!")
                return }
            guard let rePwd = setupV.rePwdTextF.text, rePwd.isValidatePwd else {
                showToast("Passwort: 6-16 Zeichen!")
                return }
            if pwd != rePwd {
                showToast("Die beiden von Ihnen eingegebenen Passwörter stimmen nicht überein!")
                return
            }            
            Task{
                
                let res = await network.request(.register(user_name: email, passwd: pwd))
                if res.isSuccess{
                    showToast("Erfolgreiche Registrierung")
                    self.loginV.isHidden = false
                    self.setupV.isHidden = true
                    self.type = 1
                    self.loginBtn.setImage(UIImage(named: "login"), for: .normal)
                }
            }
        }else{
            //登录
            guard let account = loginV.accountTextF.text, account.isValidEmail else {
                showToast("Fehler im E-Mail-Format!")
                return
            }
            guard let pwd = loginV.pwdTextF.text, pwd.isValidatePwd else {
                showToast("Passwort: 6-16 Zeichen!")
                return
            }
            Task{
                
                let res = await network.request(.login(user_name: account, passwd: pwd), type: LoginModel.self)
                if let md = res.model, res.isSuccess{
                    showToast("Anmeldung erfolgreich")
                    UserDefaultsManager.setString(md.token, forKey: .token)
                    UserDefaultsManager.setString(md.username, forKey: .userName)
                    UIApplication.window?.rootViewController = BaseTabBarVC()
                }
            }
        }
    }
    
    private func setupUI(){
        
        bottomView.addSubviews([
            titleLabel,
            subLabel,
            loginV,
            setupV,
            checkButton,
            activeLabel,
            loginBtn
        ])
        logoImageV.addSubview(backButton)
        
        configActiveStyle()
        
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalToSuperview().offset(CGFloat.statusHeight)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(30)
            make.top.equalToSuperview().offset(35)
        }
        subLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(30)
            make.top.equalToSuperview().offset(80)
        }
        loginV.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(subLabel.snp.bottom).offset(20)
            make.height.equalTo(180)
        }
        setupV.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(subLabel.snp.bottom).offset(20)
            make.height.equalTo(180)
        }
        activeLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(65)
            make.trailing.equalToSuperview().offset(-35)
            make.bottom.equalToSuperview().offset(-(CGFloat.safe_bottom + 25))
        }
        checkButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(46)
            make.top.equalTo(activeLabel)
            make.width.height.equalTo(12)
        }
        loginBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(activeLabel.snp.top).offset(-50)
            make.width.equalTo(330)
            make.height.equalTo(55)
        }
    }
    
    private func configActiveStyle() {
        let customType = ActiveType.custom(pattern: "Benutzervereinbarung")
        let customType1 = ActiveType.custom(pattern: "Datenschutzrichtlinie")
        activeLabel.isShowUnderLine = false
        activeLabel.font = UIFont.systemFont(ofSize: 12)
        activeLabel.numberOfLines = 0
        activeLabel.textAlignment = .left
        activeLabel.enabledTypes = [customType, customType1]
        activeLabel.text = "Lesen und akzeptieren Sie die Benutzervereinbarung und Datenschutzrichtlinie von ZentriNot"
        activeLabel.textColor = .black
        activeLabel.customColor[customType] = UIColor(hexString: "#0E80FD")
        activeLabel.customColor[customType1] = UIColor(hexString: "#0E80FD")
        
        let protocolVC = ProtocolViewController()
        activeLabel.handleCustomTap(for: customType) { [weak self] str in
            protocolVC.type = 1
            self?.navigationController?.pushViewController(protocolVC, animated: true)
        }
        activeLabel.handleCustomTap(for: customType1) { [weak self] str in
            protocolVC.type = 2
            self?.navigationController?.pushViewController(protocolVC, animated: true)
        }
    }

    private lazy var backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage(UIImage(named: "back"), for: .normal)
        v.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        return v
    }()
    private lazy var titleLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.font = UIFont.boldSystemFont(ofSize: 24)
        v.text = "Melden Sie sich an"
        return v
    }()
    private lazy var subLabel: UILabel = {
        let v = UILabel()
        v.textColor = UIColor(hexString: "#4F5466")
        v.font = UIFont.systemFont(ofSize: 12)
        v.text = "Willkommen zurück, du hast uns gefehlt"
        return v
    }()
    private lazy var loginBtn: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage(UIImage(named: "login"), for: .normal)
        v.addTarget(self, action: #selector(clickLoginButton), for: .touchUpInside)
        return v
    }()
    private lazy var loginV: LoginView = {
        let v = LoginView()
        return v
    }()
    private lazy var setupV: SetupView = {
        let v = SetupView()
        v.isHidden = true
        return v
    }()
    private lazy var checkButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage(UIImage(named: "login_check"), for: .normal)
        v.setImage(UIImage(named: "login_checked"), for: .selected)
        v.addTarget(self, action: #selector(clickCheckButton), for: .touchUpInside)
        return v
    }()
    private lazy var activeLabel = ActiveLabel()
}
